package com.neusoft.core;

import lombok.Data;

import java.math.BigDecimal;

@Data
public class VirtualWallet {
    private Integer walletId;  // 从int改为Integer
    private String userId;
    private Long createTime = System.currentTimeMillis();
    private BigDecimal balance = BigDecimal.ZERO;
    private boolean isAllowedOverdraft = true;
    private BigDecimal overdraftAmount = BigDecimal.ZERO;
    private BigDecimal frozenAmount = BigDecimal.ZERO;
    
    public VirtualWallet(Integer preAllocatedId) {  // 修改构造函数参数类型
        this.walletId = preAllocatedId;
    }
    
    public BigDecimal balance() {
        return this.balance;
    }
    public void freeze(BigDecimal amount) {
        if (amount.compareTo(this.balance) > 0) {
            throw new IllegalArgumentException("余额不足，无法冻结。");
        }
        this.frozenAmount = this.frozenAmount.add(amount); // 修复
    }
    public void unfreeze(BigDecimal amount) {
        this.frozenAmount = this.frozenAmount.subtract(amount); // 修复
        if (this.frozenAmount.compareTo(BigDecimal.ZERO) < 0) {
            this.frozenAmount = BigDecimal.ZERO;
        }
    }
    public void increaseOverdraftAmount(BigDecimal amount) {
        this.overdraftAmount = this.overdraftAmount.add(amount); // 修复
    }
    public void decreseOverdraftAmount(BigDecimal amount) {
        this.overdraftAmount = this.overdraftAmount.subtract(amount); // 修复
        if (this.overdraftAmount.compareTo(BigDecimal.ZERO) < 0) {
            this.overdraftAmount = BigDecimal.ZERO;
        }
    }
    public void closeOverdraft() {
        isAllowedOverdraft = false;
    }
    public void openOverdraft() {
        isAllowedOverdraft = true;
    }
    public BigDecimal getAvaliableBalance() {
        BigDecimal totalAvaliableBalance = this.balance.subtract(this.frozenAmount);
        if (isAllowedOverdraft) {
            totalAvaliableBalance = totalAvaliableBalance.add(this.overdraftAmount); // 修复
        }
        return totalAvaliableBalance;
    }
    public void debit(BigDecimal amount) {
        BigDecimal totalAvaliableBalance = getAvaliableBalance();
        if (totalAvaliableBalance.compareTo(amount) < 0) {
            throw new RuntimeException();
        }
        this.balance = this.balance.subtract(amount); // 修复：必须重新赋值
    }
    public void credit(BigDecimal amount) {
        if (amount.compareTo(BigDecimal.ZERO) < 0) {
            throw new RuntimeException();
        }
        this.balance = this.balance.add(amount); // 重新赋值
    }
}
